//! 服务模块
//! 包含各种业务服务实现

pub mod auth_service;

// 导出公共接口
pub use auth_service::{AuthService, AuthServiceHandle, AuthConfig, RealtimeAuthMiddleware};

use std::sync::Arc;

/// 服务提供者接口
/// 对应C#版本IServiceProvider
pub trait IServiceProvider: Send + Sync {
    /// 获取指定类型的服务实例
    fn get_service(&self, type_id: std::any::TypeId) -> Option<Arc<dyn std::any::Any + Send + Sync>>;
    
    /// 获取指定类型的必需服务实例
    fn get_required_service(&self, type_id: std::any::TypeId) -> Arc<dyn std::any::Any + Send + Sync>;
}

/// 简单的服务提供者实现
/// 对应C#版本ServiceProvider
#[derive(Default)]
pub struct ServiceProvider {
    services: std::collections::HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>,
}

impl ServiceProvider {
    /// 创建新的服务提供者实例
    pub fn new() -> Self {
        Self::default()
    }
    
    /// 注册服务实例
    pub fn register_service<T: Send + Sync + 'static>(&mut self, service: Arc<T>) {
        self.services.insert(std::any::TypeId::of::<T>(), service);
    }
}

impl IServiceProvider for ServiceProvider {
    fn get_service(&self, type_id: std::any::TypeId) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
        self.services.get(&type_id).cloned()
    }
    
    fn get_required_service(&self, type_id: std::any::TypeId) -> Arc<dyn std::any::Any + Send + Sync> {
        self.get_service(type_id)
            .expect(&format!("Required service with type_id {:?} not found", type_id))
    }
}

// 便利函数，提供类型安全的服务获取
impl ServiceProvider {
    /// 获取指定类型的服务实例（类型安全版本）
    pub fn get_service_typed<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
        self.get_service(std::any::TypeId::of::<T>())
            .and_then(|service| service.downcast::<T>().ok())
    }
    
    /// 获取指定类型的必需服务实例（类型安全版本）
    pub fn get_required_service_typed<T: Send + Sync + 'static>(&self) -> Arc<T> {
        self.get_service_typed::<T>()
            .expect(&format!("Required service of type {} not found", std::any::type_name::<T>()))
    }
}